# -*- coding: utf-8 -*-
import logging
import re
from enum import Enum

import requests


class DrivingRouteService:
    def __init__(self, api_key):
        self.base_url = "https://api.map.baidu.com/directionlite/v1/driving"
        self.api_key = api_key
        self.logger = logging.getLogger(__name__)

    class DrivingTactics(Enum):
        RECOMMEND = 0
        LESS_TIME = 1
        HIGHWAY = 2
        NO_HIGHWAY = 3
        AVOID_CONGESTION = 4
        EXPRESSWAY = 5
        SAVE_MONEY = 6
        TRUCK = 7
        AVOID_TRAFFIC_LIMIT = 8
        PRIORITY_FIRST_ROAD = 9
        AVOID_SPECIAL_AREA = 10
        NO_AVOID_SPECIAL_AREA = 11
        PRIORITY_EXPRESSWAY = 12

    def validate_coordinate(self, coord):
        if not re.match(r'^-?\d{1,2}\.\d{1,6},-?1?\d{1,2}\.\d{1,6}$', coord):
            self.logger.error(f"坐标格式错误: {coord}")
            return False
        try:
            lat, lng = map(float, coord.split(','))
            return -90 <= lat <= 90 and -180 <= lng <= 180
        except ValueError:
            return False

    def get_driving_route(self, origin, destination, tactics=0, **kwargs):
        if tactics not in [t.value for t in DrivingTactics]:
            raise ValueError("驾驶策略参数错误，取值范围0-12")
        if not all(self.validate_coordinate(c) for c in [origin, destination]):
            raise ValueError("坐标格式应为'纬度,经度'")

        params = {
            'origin': origin,
            'destination': destination,
            'ak': self.api_key,
            'tactics': tactics,
            **kwargs
        }

        try:
            response = requests.get(self.base_url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()

            if data.get('status') != 0:
                error_msg = data.get('message', '未知错误')
                self.logger.error(f"百度API错误: {error_msg}")
                return None

            return {
                'distance': route['distance'],
                'duration': route['duration'],
                'toll': route.get('toll', 0),
                'steps': [step['instruction'] for step in route['steps']]
            }

        except requests.exceptions.RequestException as e:
            self.logger.error(f"请求异常: {str(e)}")
            return None
        except (KeyError, IndexError) as e:
            self.logger.error(f"响应解析异常: {str(e)}")
            return None

    # 新增道路类型映射表
    ROAD_TYPE_MAP = {
        0: '高速路', 1: '城市高速路', 2: '国道',
        3: '省道', 4: '县道', 5: '乡镇村道',
        6: '其他道路', 7: '九级路', 8: '轮渡航线', 9: '行人道路'
    }

    # 新增转向指示映射表
    TURN_DIRECTION_MAP = {
        0: '无效', 1: '直行', 2: '右前方转弯',
        3: '右转', 4: '右后方转弯', 5: '掉头',
        6: '左后方转弯', 7: '左转', 8: '左前方转弯',
        9: '左侧', 10: '右侧', 11: '分歧左',
        12: '分歧中央', 13: '分歧右', 14: '环岛',
        15: '进渡口', 16: '出渡口'
    }

    def _parse_api_response(self, data):
        result = data['result']
        route = result['routes'][0]

        return {
            'origin': result['origin'],
            'destination': result['destination'],
            'distance': route['distance'],
            'duration': route['duration'],
            'toll': route.get('toll', 0),
            'traffic_condition': self._parse_traffic_status(route.get('traffic_condition')),
            'restriction_info': {
                'status': route.get('restriction_info', {}).get('status', 0)
            },
            'steps': [self._parse_step(s) for s in route['steps']]
        }

    def _parse_step(self, step):
        return {
            'leg_index': step.get('leg_index', 0),
            'direction': self._parse_direction(step.get('direction', 0)),
            'turn': self.TURN_DIRECTION_MAP.get(step.get('turn', 0), '未知转向'),
            'distance': step['distance'],
            'duration': step['duration'],
            'road_types': [self.ROAD_TYPE_MAP.get(int(rt)) for rt in step.get('road_types', '').split(',') if rt],
            'instruction': step['instruction'],
            'start_location': step['start_location'],
            'end_location': step['end_location'],
            'path': step.get('path', []),
            'traffic_condition': self._parse_traffic_status(step.get('traffic_condition', {}))
        }

    def _parse_direction(self, direction):
        start_angle = direction * 30
        return f'{start_angle}°-{start_angle+30}°'

    def _parse_traffic_status(self, condition):
        status_map = ['无路况', '畅通', '缓行', '拥堵', '严重拥堵']
        return {
            'status': status_map[condition.get('status', 0)],
            'geo_cnt': condition.get('geo_cnt', 0)
        }

# 使用示例
if __name__ == "__main__":
    service = DrivingRouteService(api_key="47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr")
    result = service.get_driving_route(
        origin="40.01116,116.339303",
        destination="39.936404,116.452562"
    )
    print(result)